<?php
class Search_Form_BoatRefineForm extends Ac_Form
{
    private $settings;


    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        array('Label', array()),
        //array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'inputText')),
    );

    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'select')),
    );

    protected $formDecorators = array(
        'FormElements',
  //      array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
        array('Description', array('placement' => 'prepend')),
        'Form',

    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'checkbox')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        //array(array('innerHTmlTag' => 'HtmlTag'), array('tag' => 'div', 'class' => 'checkbox'))
        //array('HtmlTag', array('tag' => 'dl')),
    );


    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
    );


    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        //array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'button')),
        //array('HtmlTag', array('class' => 'inputText')),
    );

    public function __construct($options = array())
    {
        $this->settings = (object) (!empty($options['settings']) ? $options['settings'] : array());
        parent::__construct($options);
    }

    protected function seller()
    {
        $form1 = $this->getNewSubForm();

        // Prefered Seller
        $form1->addElement('radio', 'saleby', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => array(
                'Dealer' => 'Dealer',
                'Owner' => 'Owner',
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'value'      => $this->getSetting('saleby'),
            'required'   => true,
        ));

        $form1->addDecorator('fieldset', array('class' => 'narrow'));
        $form1->setLegend('Preferred Seller');
        $this->addSubForm($form1, 'seller');
    }

    protected function button()
    {
        $form2 = $this->getNewSubForm();
        $form2->setDecorators(
                array('FormElements')
        );
        // Submit Button
        $form2->addElement('button', 'v', array(
            'required'   => false,
            'ignore'     => true,
            'type'       => 'submit',
            'label'      => 'Go!',
            'decorators'  => array(
                    'Errors',
                    'ViewHelper',
                    array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'button')),
            )
        ));

        $this->addSubForm($form2, 'key_search_tools2');
    }

    protected function wantTo()
    {
        $form1 = $this->getNewSubForm();

        // Want to
        $form1->addElement('radio', 'buy_rent', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => array(
                'Rent' => 'Rent',
                'Buy' => 'Buy',
                'Both' => 'Both',
            ),
            'separator' => ' ',
            'Description' => 'I want to',
            'decorators' => array(
                    'ViewHelper',
                    'Errors',
                    // 'Description'
                    array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                    array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'radio')),
            ),
            'value'      => $this->getSetting('buy_rent'),
            'required'   => true,
        ));
        $form1->getElement('buy_rent')->removeDecorator('label');

        $form1->addDecorator('fieldset', array('class' => 'narrow'));
        $form1->setLegend('Narrow Your Search');
        $this->addSubForm($form1, 'want_to');
    }

    protected function performances()
    {
        $form1 = $this->getNewSubForm();

        $locations = array('All');
        $locs = Model_Location::all()->sort(array('path' => 1));
        $parent = '';
        foreach($locs as $k => $loc) {

            if (count($loc->path) == 1) {
                $parent = $loc->name;
                $locations[$loc->name] = array();
            } else {

                //$parent = (string) $loc->path[0];
                $tmp    = !empty($locations[(string) $parent]) ? $locations[(string) $parent] : array();

                $tmp[$k]         = (string) $loc->name;
                //echo '<pre>';
                //print_r($tmp);
                $locations[(string) $parent] = $tmp;
            }
        }
        // --> District
        $form1->addElement('select', 'district', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'    => $this->elementSelectDecorators,
            'multiOptions'  => $locations,
            'required'      => false,
            'label'         => 'Area/District',
            'value'         => $this->getSetting('district'),
        ));
        
        // Boat Type
        $boattype = Model_Listing_Boat::getBoatType();
        $selected_boattype = $this->getSetting('boattype');
        if (empty($selected_boattype)) {
            reset($boattype);
            $selected_boattype = key($boattype);
        }
        $form1->addElement('select', 'key_search_tool_boattype', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => $boattype,
            'required'     => false,
            'label'        => 'Boat Type',
            'value'        => $this->getSetting('boattype'),
        ));

        // Boat Category
        $form1->addElement('select', 'key_search_tool_boatcategory', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getBoatCategory($selected_boattype),
            'required'     => false,
            'label'        => 'Boat Category',
            'value'        => $this->getSetting('boatcategory'),
        ));

        // Make
        $form1->addElement('autoComplete', 'key_search_tool_make', array(
                    'jQueryParams' => array('source' => '/search/get-attribute?c=boats&f=model'),
                    'label'       => 'Make',
                    'decorators' => array(
                            'Errors',
                            'UiWidgetElement',
                            array('Label', array('escape' => false)),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'text')),
                    ),
                    'value'        => $this->getSetting('make'),
                )
        );

        /*$form1->addElement('select', 'key_search_tool_make', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => $make,
            'required'     => false,
            'label'        => 'Make',
            'value'        => $this->getSetting('make'),
        ));*/

        // Feature
        $form1->addElement('select', 'key_search_tool_feature', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getFeature(),
            'required'     => false,
            'label'        => 'boat-form-feature',
            'value'        => $this->getSetting('feature'),
        ));

        // Length
        $form1->addElement('select', 'key_search_tool_length', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getLength(),
            'required'     => false,
            'label'        => 'Length',
            'value'        => $this->getSetting('length'),
        ));

        // Sale Price
        /*
        $form1->addElement('jqslider', 'key_search_tool_price', array(
                    'jQueryParams' => array(
                        'min'      => $this->getSetting('price_min') !== null ? $this->getSetting('price_min') : 0,
                        'max'      => $this->getSetting('price_max') !== null ? $this->getSetting('price_max') : 2000000,
                        'values'   => $this->getSetting('price_start') !== null ? $this->getSetting('price_start') : array('0', '2000000'),
                        'currency' => '$HKD',
                        'range'    => true,
                        'step'     => 1000,
                        ),
                    'label'       => 'Price (HKD$)',
                    'decorators' => array(
                            'Errors',
                            'UiWidgetElement',
                            array('Label', array('escape' => false)),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'slide')),
                    )
                )
        );
        */
        $form1->addElement('textRange', 'price', array(
                    'label'       => 'Price (HKD)',
                    'value'       => $this->getSetting('price_start') !== null ? $this->getSetting('price_start') : array(),
                    'class'       => array('class' => 'text-range'),
                    'decorators'  => array(
                            'Errors',
                            'ViewHelper',
                            array('Label', array('escape' => false)),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'text range')),
                    )
                )
        );

        // Year Manufactured
        $form1->addElement('select', 'key_search_tool_yearmanufactured', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getYearManufactured(),
            'required'     => false,
            'label'        => 'Year Manufactured',
            'value'        => $this->getSetting('yearmanufactured'),
        ));

        // No of Previous Owners
        $form1->addElement('select', 'key_search_tool_previousowners', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getPreviousOwners(),
            'required'     => false,
            'label'        => 'No of Previous Owners',
            'value'        => $this->getSetting('previousowners'),
        ));

        $form1->addElement('hidden', 'add_show', array(
            'value'       => $this->getSetting('add_show'),
            'id'          => 'add_show',
            'name'        => 'add_show',
        ));
        $form1->getElement('add_show')->removeDecorator('label');

        // --> Keyword
        /*$form1->addElement('text', 'keyword', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Keywords',
            'value'      => $this->getSetting('keyword'),
        ));

        $form1->addDisplayGroup(array('keyword', 'v'), 'key_search_tool2',
            array(
                'decorators' => array_merge($this->displayGroupDecorators, array(array('HtmlTag', array('tag' => 'div', 'class' => 'text'))))
            )
        );*/

        // --> Additional Button
        $form1->addElement('hidden', 'additional_button', array(
            'decorators'  => array(
                    'Errors',
                    'ViewHelper',
                    array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'div', 'class' => 'desc more', 'id' => 'additional_btn')),
            ),
            'Description' => '<a href="#">Additional Features »</a>',
            'value'       => $this->getSetting('key_search_tool_district'),
        ));

        $form1->addDecorator('fieldset', array('class' => 'key_search'));
        $form1->setLegend('Key Features');
        $this->addSubForm($form1, 'performances');
    }

    protected function optional()
    {
        $form1 = $this->getNewSubForm();

        // Engine Type
        $form1->addElement('select', 'key_search_tool_enginetype', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getEngineType(),
            'required'     => false,
            'label'        => 'Engine Type',
            'value'        => $this->getSetting('enginetype'),
        ));

        // Fuel Capacity
        $form1->addElement('select', 'key_search_tool_fuelcapacity', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getFuelCapacity(),
            'required'     => false,
            'label'        => 'Fuel Capacity',
            'value'      => $this->getSetting('fuelcapacity'),
        ));

        // Hull Material
        $form1->addElement('select', 'key_search_tool_hullmaterial', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getHullMaterial(),
            'required'     => false,
            'label'        => 'Hull Material',
            'value'        => $this->getSetting('hullmaterial'),
        ));

        // Fuel Type
        $form1->addElement('select', 'key_search_tool_fueltype', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getFuelType(),
            'required'     => false,
            'label'        => 'Fuel Type',
            'value'      => $this->getSetting('fueltype'),
        ));

        // Trailer Included
        $form1->addElement('select', 'key_search_tool_trailerincluded', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getTrailerIncluded(),
            'required'     => false,
            'label'        => 'Trailer Included',
            'value'        => $this->getSetting('trailerincluded'),
        ));

        // Model Year
        $form1->addElement('select', 'key_search_tool_modelyear', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Boat::getModelYear(),
            'required'     => false,
            'label'        => 'Model Year',
            'value'        => $this->getSetting('modelyear'),
        ));

        $form1->addDecorator('fieldset', array('class' => 'key_search', 'style' => 'display:none'));
        $this->addSubForm($form1, 'optional');
    }

    public function init()
    {
        parent::init();

        $this->setSubFormDecorators($this->subFormDecorators);
        $this->setDisplayGroupDecorators($this->displayGroupDecorators);

        $this->setMethod('GET');
        $this->setName('RefineSearch');

        $element = new Zend_Form_Element_Hidden('keyword');
        if (isset($_GET['keyword'])) {$element->setValue($_GET['keyword']);}
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);

        $element = new Zend_Form_Element_Hidden('small_category_list');
        if (Zend_Registry::isRegistered('category_list_selected')) {
            $selected = Zend_Registry::get('category_list_selected');
            $element->setValue($selected);
        } elseif (!empty($_GET['small_category_list'])) {
            $selected = $_GET['small_category_list'];
            $element->setValue($selected);
        } elseif (Zend_Registry::isRegistered('category_list_id')) {
            $id = Zend_Registry::get('category_list_id');
            $cat = Model_Category::find($id);
            $this->view->category = $cat;
            if (empty($cat->customization)) {
                $get['small_category_list'] = $id;
            }
            else {
                $get['small_category_list'] = $cat->customization;
            }
            $selected = $get['small_category_list'];
            $element->setValue($selected);
        }
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);

        //$this->seller();
        $this->wantto();
        $this->performances();
        $this->optional();
        $this->button();

    }

    function populate(array $values)
    {
        if (isset($_GET['performances']['add_show'])) {
            $this->settings->add_show = $_GET['performances']['add_show'];
        }
        else {
            $this->settings->add_show = '0';
        }

        //Keywords
        if (isset($values['key_search_tools']['keyword'])) {
            $this->settings->keyword = $values['key_search_tools']['keyword'];
        }
        if (isset($_GET['keyword'])) {
            if (empty($values['key_search_tools']['keyword'])) {
                $this->settings->keyword = $_GET['keyword'];
            }
        }

        //I want to
        if (isset($values['want_to']['buy_rent'])) {
            $this->settings->buy_rent = $values['want_to']['buy_rent'];
        }
        else {
            $this->settings->buy_rent = 'Both';
        }
        if (isset($values['wantto_boat'])) {
            $this->settings->buy_rent = $values['wantto_boat'];
        }

        //Sale By
        if (isset($values['seller']['saleby'])) {
            $this->settings->saleby = $values['seller']['saleby'];
        }
        if (isset($values['agency_owner_boat'])) {
            $this->settings->saleby = $values['agency_owner_boat'];
        }

        //Boat Type
        if (isset($values['performances']['key_search_tool_boattype'])) {
            $this->settings->boattype = $values['performances']['key_search_tool_boattype'];
        }
        if (isset($values['boattype'])) {
            $this->settings->boattype = $values['boattype'];
        }

        //Boat Category
        if (isset($values['performances']['key_search_tool_boatcategory'])) {
            $this->settings->boatcategory = $values['performances']['key_search_tool_boatcategory'];
        }
        if (isset($values['boatcategory'])) {
            $this->settings->boatcategory = $values['boatcategory'];
        }

        //Make
        if (isset($values['performances']['key_search_tool_make'])) {
            $this->settings->make = $values['performances']['key_search_tool_make'];
        }
        if (isset($values['make'])) {
            $this->settings->make = $values['make'];
        }

        //Feature
        if (isset($values['performances']['key_search_tool_feature'])) {
            $this->settings->feature = $values['performances']['key_search_tool_feature'];
        }

        //Length
        if (isset($values['performances']['key_search_tool_length'])) {
            $this->settings->length = $values['performances']['key_search_tool_length'];
        }

		//District
        if (isset($values['performances']['district'])) {
            $this->settings->district = $values['performances']['district'];
        }
        if (isset($values['district'])) {
            $this->settings->district = $values['district'];
        }
		
		if (!empty($_GET['keyword'])) {
			$loc = Model_Location::one(array('nm_en' => array('$regex' => $_GET['keyword'], '$options' => 'i' )));
			if (!empty($loc) && empty($this->settings->district) ) {
				$this->settings->district = $loc->_id;
			}
		}
		
        //Price
        if (isset($values['performances-price']) && isset($values['performances-price-1'])) {
            $this->settings->price_start = array($values['performances-price'], $values['performances-price-1']);
        }
        if (isset($values['price_boat']) && isset($values['price_boat-1'])) {
            $this->settings->price_start = array($values['price_boat'], $values['price_boat-1']);
        }

        //Year Manufactured
        if (isset($values['performances']['key_search_tool_yearmanufactured'])) {
            $this->settings->yearmanufactured = $values['performances']['key_search_tool_yearmanufactured'];
        }
        if (isset($values['yearmanufactured_boat'])) {
            $this->settings->yearmanufactured = $values['yearmanufactured_boat'];
        }

        //Model Year
        if (isset($values['optional']['key_search_tool_modelyear'])) {
            $this->settings->modelyear = $values['optional']['key_search_tool_modelyear'];
        }

        //No of Previous Owners
        if (isset($values['performances']['key_search_tool_previousowners'])) {
            $this->settings->previousowners = $values['performances']['key_search_tool_previousowners'];
        }

        //Engine Type
        if (isset($values['optional']['key_search_tool_enginetype'])) {
            $this->settings->enginetype = $values['optional']['key_search_tool_enginetype'];
        }

        //Hull Material
        if (isset($values['optional']['key_search_tool_hullmaterial'])) {
            $this->settings->hullmaterial = $values['optional']['key_search_tool_hullmaterial'];
        }

        //Trailer Included
        if (isset($values['optional']['key_search_tool_trailerincluded'])) {
            $this->settings->trailerincluded = $values['optional']['key_search_tool_trailerincluded'];
        }

        //Fuel Type
        if (isset($values['optional']['key_search_tool_fueltype'])) {
            $this->settings->fueltype = $values['optional']['key_search_tool_fueltype'];
        }

        //Fuel Capacity
        if (isset($values['optional']['key_search_tool_fuelcapacity'])) {
            $this->settings->fuelcapacity = $values['optional']['key_search_tool_fuelcapacity'];
        }
    }

    private function getNewSubForm()
    {
        $form = new Ac_SubForm();
        $form->setDecorators($this->subFormDecorators);
        $form->setDisplayGroupDecorators($this->displayGroupDecorators);
        return $form;
    }

    private function getSetting($name)
    {
        if (!empty($this->settings->$name)) {
            return $this->settings->$name;
        }
        return null;
    }

    public function __toString()
    {
        $str = '
            $j("#performances-key_search_tool_boattype").change(function (event) {
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"boattype", f:"model", id: $j("#performances-key_search_tool_boattype").val() },
                    function(data) {
                        $j("#performances-key_search_tool_boatcategory").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#performances-key_search_tool_boatcategory"));
                        });
                    });
           });
        ';
        $this->view->JQuery()->addJavascript($str);
        return parent::__toString();
    }
}